package com.basics.modules.security.service.Impl;

import com.basics.common.exception.BadRequestException;
import com.basics.modules.security.domain.User;
import com.basics.modules.security.security.vo.JwtUser;
import com.basics.modules.security.service.UserService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**功能描述：获取用户信息接口实现
 */
@Service("userDetailsService")
//如果其他bean调用这个方法,在其他bean中声明事务,那就用事务.如果其他bean没有声明事务,那就不用事务.
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class UserDetailsServiceImpl implements UserDetailsService {
    @Resource
    private UserService userService;
    /**
     * 根据用户名获取用户信息
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.findByName(username);
        if(user==null){
            throw new BadRequestException("账号不存在");
        }else {
            if(!user.getEnabled()){
                throw new BadRequestException("账号未激活");
            }
        }
        return createJwtUser(user);
    }

    private UserDetails createJwtUser(User user) {
        return new JwtUser(
                user.getId(),
                //用户登录账号
                user.getUsername(),
                //昵称
                user.getNickName(),
                //性别
                user.getSex(),
                //密码
                user.getPassword(),
                //头像
                user.getAvatar(),
                //邮箱
                user.getEmail(),
                //手机号
                user.getPhone(),
                //获取用户的权限
                null,
                //判断用户是否激活
                user.getEnabled(),
                //创建用户时间
                user.getCreateTime(),
                //修改密码时间
                user.getLastPasswordResetTime()
        );
    }
}
